package test3;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


public class Kitchen {
    private final ReentrantLock lock = new ReentrantLock();

//     cookCondition.await()能唤醒指定进程，是因为通过同一把锁创建了不同的Condition条件变量,
//    从而把线程放入不同Condition独立的等待队列，线程可根据不同的条件等待，
//    当条件满足时从指定等待队列(该条件对应的等待队列)中去唤醒线程
    Condition cutCondition = lock.newCondition();
    Condition cookCondition = lock.newCondition();
    Condition giveCondition = lock.newCondition();

    private String state = "cut";

    public void cut(int i) {
        lock.lock();
        try {
            while (!state.equals("cut")) {
                cutCondition.await();
            }
            System.out.println(Thread.currentThread().getName() + "开始切第"+i+"盘菜");
            TimeUnit.SECONDS.sleep(new Random().nextInt(3));
            System.out.println(Thread.currentThread().getName() + "结束切第"+i+"盘菜！");

            state="cook";
            cookCondition.signal();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void cook(int i) {
        lock.lock();
        try {
            while (!state.equals("cook")) {
                cookCondition.await();
            }
            System.out.println(Thread.currentThread().getName() + "开始炒第"+i+"盘菜");
            TimeUnit.SECONDS.sleep(new Random().nextInt(3));
            System.out.println(Thread.currentThread().getName() + "结束炒第"+i+"盘菜！");

            state="give";
            giveCondition.signal();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void give(int i) {
        lock.lock();
        try {
            while (!state.equals("give")) {
                giveCondition.await();
            }
            System.out.println(Thread.currentThread().getName() + "开始端第"+i+"盘菜");
            TimeUnit.SECONDS.sleep(new Random().nextInt(3));
            System.out.println(Thread.currentThread().getName() + "结束端第"+i+"盘菜！");

            state="cut";
            cutCondition.signal();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
